package com.wl.wuliu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wl.wuliu.entity.PasswordBody;
import com.wl.wuliu.entity.SysRole;
import com.wl.wuliu.entity.SysUser;
import com.wl.wuliu.exception.GlobalExceptionHandler;
import com.wl.wuliu.mapper.SysRoleMapper;
import com.wl.wuliu.mapper.SysUserMapper;
import com.wl.wuliu.result.AjaxResult;
import com.wl.wuliu.service.SysUserService;
import com.wl.wuliu.utils.StringUtils;
import com.wl.wuliu.weixin.AccessToken;
import com.wl.wuliu.weixin.WeixinHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @Author: gutaozhen
 * @Date: 2024/5/15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<SysUser> findList(SysUser sysUser) {

        return sysUserMapper.findList(sysUser);
    }

    @Override
    public SysUser selectUserByUserName(String userName) {
        return getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, userName));
    }

    @Override
    public AjaxResult saveSysUser(SysUser sysUser) {

        //校验手机号码是否已存在
        SysUser querySysUser = new SysUser();
        querySysUser.setMobile(sysUser.getMobile());
        SysUser user = this.findSysUser(querySysUser);
        if (user != null) {
            return AjaxResult.error("该手机号码已存在。");
        }

        sysUser.preInsert();
        sysUser.setStatus("0");
        sysUser.setUserName(sysUser.getWechat());
        save(sysUser);

        //设置权限
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_key", sysUser.getRoleKey());
        SysRole sysRole = sysRoleMapper.selectOne(queryWrapper);
        sysRoleMapper.saveUserRole(sysUser.getId(), sysRole.getId());

        log.info("保存用户信息成功，保存的用户id为{}",sysUser.getId());

        return AjaxResult.success();
    }

    @Override
    public AjaxResult updatePwd(PasswordBody passwordBody) {

        SysUser sysUser = getById(passwordBody.getUserId());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在。");
        }

        if (!passwordBody.getOldPassword().equals(sysUser.getPassword())) {
            return AjaxResult.error("原始密码不正确。");
        }

        SysUser updateSysUser = new SysUser();
        updateSysUser.setId(passwordBody.getUserId());
        updateSysUser.setPassword(passwordBody.getNewPassword());

        updateById(updateSysUser);
        log.info("修改密码成功，用户id为：{},密码修改为：{}",passwordBody.getUserId(), passwordBody.getNewPassword());


        return AjaxResult.success("修改成功。");
    }

    @Override
    public SysUser findSysUser(SysUser sysUser) {

        return sysUserMapper.findSysUser(sysUser);
    }

    @Override
    public SysUser getWeixinUserInfo(String code) {

        //根据code获取用户的openid
        AccessToken accessToken = WeixinHttpUtil.getAccessToken(code);
        if (accessToken != null && !StringUtils.isEmpty(accessToken.getOpenId())) {
            //根据openid去查询当前的用户是否存在
            SysUser sysUser = sysUserMapper.findSysUserByOpenId(accessToken.getOpenId());
            if (sysUser != null) {
                return sysUser;
            }else {
                //根据openid去微信获取用户的详细信息
                return WeixinHttpUtil.getUserInfo(accessToken.getAccessToken(), accessToken.getOpenId());
            }
        }

        return new SysUser();
    }
}
